//
//  HttpRequestManager.m
//  BossSystem
//
//  Created by hzyd-wlj on 14-7-30.
//  Copyright (c) 2014年 hzyd. All rights reserved.
//

#import "HttpRequestManager.h"
#import "SVHTTPClient.h"
#import "SVProgressHUD.h"
//#import "Define.h"

NSString *const HttpRequestManagerDidGetNeedReloginNotificationKey = @"HttpRequestManagerDidGetNeedReloginNotificationKey";

@implementation HttpRequestManager
/**
 *  企信服务器basePath：KWebBasePath为这个
 *
 *  @param methodName
 *  @param parameters
 *  @param completedMainBlock
 */
+ (void)postMethod:(NSString *)methodName parameters:(NSDictionary *)parameters completedMainBlock:(completedMainBlock)completedMainBlock
{
    //TODO:优化请求错误的处理
    [[SVHTTPClient sharedClient] POST:methodName parameters:parameters completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
        NSString *errMsg;
        NSLog(@"%@",response);
        if(response == nil)
        {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }else{
            NSDictionary *responsed = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:nil];
//            DLog(@"respond = %@",responsed);
            //FIXME:
            errMsg = [self isCurrentLanguageEnglish]?@"英文错误信息":@"中文错误信息";
            if (!error) {
                if ([[responsed[@"status"] stringValue] isEqualToString:@"1"]) {
                    completedMainBlock(YES,responsed,errMsg);
                }else{
                    completedMainBlock(NO,responsed,responsed[@"status"]);
                }
            }else{
                //网络方面的错误
                errMsg = [NSString stringWithFormat:@"网络错误或服务器未响应!（%ld:%@）",(long)error.code,[error localizedDescription]];
                [SVProgressHUD showErrorWithStatus:errMsg];
                completedMainBlock(NO,nil,errMsg);
                NSLog(@"网络请求错误，服务器未响应%@",errMsg);
            }
        }
    }];
}
/**
 *  get请求，企信服务器basePath：KQXWebBasePath为这个
 *
 *  @param methodName
 *  @param parameters
 *  @param completedMainBlock
 */
+ (void)getMethod:(NSString *)methodName parameters:(NSDictionary *)parameters completedMainBlock:(completedMainBlock)completedMainBlock
{
    [[SVHTTPClient sharedClient] GET:methodName parameters:parameters completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
        NSString *errMsg;
        //FIXME:
        if(response == nil)
        {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }else{
            NSDictionary *responsed = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:nil];
            errMsg = [self isCurrentLanguageEnglish]?@"英文错误信息":@"中文错误信息";
            if (!error) {
                if ([[responsed[@"status"] stringValue] isEqualToString:@"1"]) {
                    completedMainBlock(YES,responsed,errMsg);
                }else{
                    completedMainBlock(NO,responsed,responsed[@"status"]);
                }
            }else{
                //网络方面的错误
                errMsg = [NSString stringWithFormat:@"网络错误或服务器未响应!（%ld:%@）",(long)[error code],[error localizedDescription]];
                [SVProgressHUD showErrorWithStatus:errMsg];
                completedMainBlock(NO,nil,errMsg);
                NSLog(@"网络请求错误%@",errMsg);
            }
        }
    }];
}

+ (BOOL)isCurrentLanguageEnglish
{
    NSArray *languages = [NSLocale preferredLanguages];
    return [[languages objectAtIndex:0] isEqualToString:@"en"];
}

+ (void)netWorkManagerWithUrl:(NSString *)urlString success:(SuccessBlock)successB error:(ErrorBlock)errorB{
    //1.创建URL
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //2.创建request
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3.开启网络请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            successB(obj);
        }else {
            errorB(connectionError);
        }
        
    }];
}
@end
